package com.wwz.leetcode;

import org.junit.Test;

/**
 * 给定一个n个元素有序的（升序）整型数组nums 和一个目标值target ，写一个函数搜索nums中的 target，如果目标值存在返回下标，否则返回 -1。
 * 二分查找 logn
 */
public class LeetCode709 {

    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        while (left <= right) {

            mid = (right - left) / 2 + left;
            if (nums[mid] == target) {
                return mid;
            }
            if (target > nums[mid]) {
                left = mid + 1;
            } else if (target < nums[mid]) {
                right = mid - 1;
            }
        }
        return -1;
    }

    @Test
    public void test(){
        int[] nums = {-1,0,3,5,9,12};
        int search = search(nums, 9);
        System.out.println(search);
    }

}
